<?php
App::uses('CakeEmail', 'Network/Email');
class UsersController extends AppController {
  //public $scaffold;
  public $helpers = array('Html', 'TWSForm');
  public $components = array('Session', 'Util');
  public $name = 'Users';
  public $paginate;
  public $activeOptions= array('Y' => 'Yes', 'N' => 'No');
  public $verificationOptions= array('Y' => 'Yes', 'N' => 'No');

  function __construct($request=null, $response=null) {
    parent::__construct($request, $response);
    $this->paginate = array(
        'limit' => Configure::read('App.pageResultLimit'),
        'order' => array(
            'User.last_name' => 'asc', 'User.first_name' => 'asc'
            ));
  }

  function admin_index(){
    $this->layout ='admin';
    $this->set('title_for_layout','Users');
    $this->set('users', $this->paginate('User'));
  }

  function admin_edit($id=null) {
    $errorOccurred = false;
    $this->layout = 'admin';
    $this->set('title_for_layout', 'Edit User');
    $this->set('activeOptions', $this->activeOptions);
    $this->set('verificationOptions', $this->verificationOptions);
    //getting companies
    $this->loadModel('Company');
    $this->set('companies', $this->Company->find('list', array('fields'=> array('Company.id','Company.name'), 'order'=>array('name'=>'asc')  )));
    //getting roles
    $this->loadModel('Role');
    $roles = $this->Role->query('Select Role.role_name from roles as Role order by Role.role_name ASC');
    $this->set('roles', $roles);
    $this->User->id = $id;
    $userData = $this->User->read();
    if ($this->request->is('get')) {
       $this->request->data = $userData;
    } else {
      //check for delete announcement
      if (isset($this->request->data['deleteBtn'])) {
        $this->admin_delete($id);
      } else {
        $data = $this->_processRequestData($this->request);
        $this->User->set($data);
        //if ($this->User->validates(array('first_name','last_name'))) { //TODO validation
        //getting roles
        if (empty($data['User']['first_name']) || empty($data['User']['last_name'])) {
          $errorOccurred = true;
          $this->Session->setFlash('First and Last name is required.');
        } else {
          $userRoles = array();
          for ($i = 0; $i < sizeof($roles); $i++) {
            if (isset($this->request->data['role' . $i])) {
              array_push($userRoles, $this->request->data['role' . $i]);
            }
          }
          if (empty($userRoles)) {
            $this->Session->setFlash('Please select at least one role for the user.');
            $errorOccurred = true;
          } else {
            //Checking for first activation
            $firstActivation = false;
            if(empty($userData['User']['firstActivated'])){
              $firstActivation=true;
              $activationDate =new DateTime();
              $data['User']['first_activated']=$activationDate->format("Y-m-d");
              //create category
              $this->loadModel('Category');
              $this->loadModel('Company');
              $company = $this->Company->find('first',array('conditions'=>array('Company.id'=>$data['User']['company_id'])));
              if(!empty($company)){
                $categoryData = array("Category"=>array('name'=>$company['Company']['name'], 'description'=>$company['Company']['name'],'company_id'=>$company['Company']['id']));
                $this->Category->save($categoryData, false);
                //Setting company of user
                $data['User']['company_id']=$company['Company']['id'];
              }
            }
            if ($this->User->save($data, false, array('first_name', 'last_name', 'active', 'verified','company_id','first_activated'))) {
              //Saving Roles
              $this->loadModel('UserRoles');
              //deleting existing roles
              $result = $this->UserRoles->deleteAll(array('UserRoles.user_id' => $id), false);
              //inserting new entries
              foreach ($userRoles as $userRole) {
                $this->UserRoles->create();
                $this->UserRoles->save(array('UserRoles' => array('user_id' => $id, 'role_name' => $userRole)));
              }
              $message = 'The record was successfully updated.';
              if($firstActivation){
                if($this->_sendAccountConfirmationEmail($userData)) {
                  $message .= ' The user has been activated and an email was sent to notify the user of account activation.';
                } else {
                  $message .= ' The user has been activated however an error occurred while attempting to send an automatic email notifying the user of account activation. Please notify the user that their account was activated.';
                }
              }
              $this->Session->setFlash($message);
              $this->redirect(array('action' => 'index'));
            } else {
              $this->Session->setFlash('An error occurred and the record was not successfully updated.');
              $errorOccurred = true;
            }
          }
        }
        if ($errorOccurred) {
          $this->User->id = $id;
          $dataModified = $this->User->read();
          $dataModified['User']['first_name'] = $data['User']['first_name'];
          $dataModified['User']['last_name'] = $data['User']['last_name'];
          $dataModified['User']['verified'] = $data['User']['verified'];
          $dataModified['User']['active'] = $data['User']['active'];
          $this->request->data = $dataModified;
        }

        $this->render('admin_edit');
        ///////////////////
      }
    }
  }

  //admin
  function admin_delete($id) {
    if ($this->User->delete($id)) {
      $this->Session->setFlash('The record has been deleted.');
      $this->redirect(array('action' => 'index'));
    }
  }
  
   function _sendAccountConfirmationEmail($user) {
    $retVal = false;
     if (is_array($user)){
      $data = $user;
      //Sending verification email
      App::import('Helper', 'Html');
      $view = new View($this);
      $html = $view->loadHelper('Html');
      $email = new CakeEmail('tws');
      $email->to($data['User']['email'],$data['User']['first_name'].' '.$data['User']['last_name']);
      $email->subject("Account setup complete at the ".Configure::read('App.name'). " website");
      $email->template('activate_account_confirmation');
      $email->from(array(Configure::read('App.emailDefaultFrom')=>Configure::read('App.name')));
      $email->transport('Mail')->viewVars(array('name'=>$data['User']['first_name'].' '.$data['User']['last_name'],'clubName'=>Configure::read('App.name')));
      $retVal = $email->send();
    }
    return $retVal;
  }
 

}
?>
